package com.imagination.applet.domain.revenue.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.imagination.applet.domain.revenue.order.model.OrderType;
import com.imagination.applet.domain.revenue.order.model.UserOrder;
import com.imagination.applet.domain.revenue.order.repository.UserOrderRepository;
import com.imagination.applet.domain.revenue.order.service.OrderService;
import com.imagination.applet.domain.support.payment.service.PayService;
import com.imagination.applet.domain.user.model.User;
import com.imagination.applet.domain.user.repository.UserRepository;
import com.imagination.applet.domain.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Currency;
import java.util.Map;
import java.util.Optional;

@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class OrderServiceImpl implements OrderService {

    private final UserOrderRepository userOrderRepository;
    private final UserRepository userRepository;

    @Override
    public UserOrder createOrder(Long userId, OrderType orderType, BigDecimal amount, Currency currency, Map<String, Object> extensions) {
        final String traceNo = generateTransNo(orderType);
        return saveOrder(userId, traceNo, orderType, amount.multiply(BigDecimal.valueOf(100)).intValue(), currency, extensions);
    }

    @Override
    public UserOrder queryOrder(Long userId, String traceNo) {
        return null;
    }

    @Override
    @Transactional
    public UserOrder wxCallBackOrder(String traceNo, JSONObject resData) {
        UserOrder user = userOrderRepository.findByTraceNo(traceNo);
        user.setStatus(1);
        user.setResData(resData.toJSONString());
        userOrderRepository.save(user);
        // 增加星星值
        Optional<User> userData = userRepository.findById(user.getUserId());
        JSONObject extensions = JSONObject.parseObject(user.getExtensions());
        User current = userData.get();
        int count = userOrderRepository.countByUserIdAndStatus(user.getUserId(), 1);
        // 邀请注册，第一次支付给上级加30
        System.out.println(current.getId()+"充值成功次数:"+count);
        System.out.println(current.getId()+"上级用户:"+current.getParentId());
        if(count == 1){
            if(current.getParentId() != null){
                Optional<User> parentOpt = userRepository.findById(current.getParentId());
                User parent = parentOpt.get();
                System.out.println("查询出上级用户"+parent.getParentId()+"星星熟"+parent.getStarCount());
                parent.setStarCount(parent.getStarCount() + 30);
                System.out.println("修改为"+parent.getStarCount());
                userRepository.saveAndFlush(parent);
                System.out.println("修改成功");
            }
        }
        // 支付成功增加星星
        current.setStarCount(current.getStarCount() + extensions.getInteger("starNumber"));
        userRepository.saveAndFlush(current);
        return user;
    }


    private UserOrder saveOrder(Long userId, String transNo, OrderType orderType, Integer amount, Currency currency, Map<String, Object> extensions) {
        UserOrder order = UserOrder.builder()
                .userId(userId)
                .traceNo(transNo)
                .orderType(orderType)
                .amount(amount)
                .currency(currency)
                .extensions(JSONObject.toJSONString(extensions))
                .build();
        return userOrderRepository.save(order);
    }

    private String generateTransNo(OrderType ot) {
        return ot.getCode() + System.currentTimeMillis();
    }
}
